package com.vnp.cooking;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.vnp.cooking.adapter.NhabepGridAvapter;
import com.vnp.cooking.adapter.NhabepListAdpater;
import com.vnp.cooking.bean.ObjAttribute;
import com.vnp.cooking.bean.ObjCookpad;
import com.vnp.cooking.httpclient.HttpClientHelper;
import com.vnp.cooking.httpclient.MyJsonHttpResponseHandler;
import com.vnp.cooking.utils.PreferenceHelper;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class ResultLoaimonActivity extends Activity implements OnClickListener, OnScrollListener{
	
	ListView listResult;
	GridView gridResult;
	ImageButton btnBack;
	NhabepListAdpater listAdapter;
	NhabepGridAvapter gridAdapter;
	ImageButton btnSortDisplay;
	
	// load more
	boolean isLoading = false;
	Button btnLoadmore;
	int mPage = 0;
	
	ArrayList<ObjCookpad> objCookpads = new ArrayList<ObjCookpad>();
	
	// footer view
	View footerMain;
	Button btnLoadMore;
	ProgressBar progressBarLoadmore;
	PreferenceHelper preferenceHelper;
	ProgressBar progressBar, progressBar2;
	TextView noRs;
	TextView titleScreen;
	
	// display
	ArrayList<ObjAttribute> objAttributes = new ArrayList<ObjAttribute>();
	String alias, name, aliasDetail;
	
	View actionbar;
	private int preLast;
	Handler mHandler = new Handler();
	Runnable r = new Runnable() {
		
		@Override
		public void run() {
			layCongthuctheothanhphan(mPage);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_result_loaimon);
		
		preferenceHelper = new PreferenceHelper(this);
		
		alias = getIntent().getStringExtra("alias");
		name = getIntent().getStringExtra("title");
		aliasDetail = getIntent().getStringExtra("aliasDetail");
		
		actionbar = (View) findViewById(R.id.actionbar);
//		preferenceHelper.setID("1118396");
		titleScreen = (TextView) findViewById(R.id.title_result_loaimon);
		noRs = (TextView) findViewById(R.id.txt_no_result);
		listResult = (ListView) findViewById(R.id.list_rs);
		gridResult = (GridView) findViewById(R.id.gridview);
		
		mHandler.post(r);
		
		
		btnBack = (ImageButton) findViewById(R.id.btn_back);
		btnSortDisplay = (ImageButton) findViewById(R.id.btn_sort_display);
		btnSortDisplay.setEnabled(false);
		progressBar = (ProgressBar) findViewById(R.id.progressBar1);
		progressBar2 = (ProgressBar) findViewById(R.id.progressBar2);
		// add footer listview
		addFooterView();
		
		gridAdapter = new NhabepGridAvapter(this, objCookpads);
		listAdapter = new NhabepListAdpater(this, objCookpads);
		
		gridResult.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				int lastItem  = firstVisibleItem + visibleItemCount;
				if (lastItem == totalItemCount){
					if (preLast != lastItem) {
						int last_pos = gridResult.getLastVisiblePosition();
						if(last_pos>=objCookpads.size()-1&& !isLoading){
							if (gridResult.getVisibility() == View.VISIBLE) {
								progressBar2.setVisibility(View.VISIBLE);
							}
							layCongthuctheothanhphan(++mPage);
						}
						preLast = lastItem;
					}
				}
				
			}
		});
		
		init();
	}
	
	void init() {
		titleScreen.setText(name);
		btnSortDisplay.setOnClickListener(this);
		btnBack.setOnClickListener(this);
		listResult.setAdapter(listAdapter);
		listResult.setOnScrollListener(this);
		actionbar.setOnClickListener(this);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		
		case R.id.actionbar:
			listResult.smoothScrollToPosition(0);
			break;
		case R.id.btn_back:
			closeActivity();
			break;

		case R.id.btn_sort_display:
			changeListGrid();
			break;
		
		case R.id.btn_load_more:
			mPage = mPage + 1;
			layCongthuctheothanhphan(mPage);
			progressBarLoadmore.setVisibility(View.VISIBLE);
			btnLoadMore.setText("Đang lấy thêm công thức...");
			break;
		}
	}
	
	// change list and grid
		public void changeListGrid() {
			if (gridResult.getVisibility() == View.VISIBLE) {
				gridResult.setVisibility(View.GONE);
				listResult.setVisibility(View.VISIBLE);
				listResult.setAdapter(listAdapter);
				btnSortDisplay.setImageResource(R.drawable.ic_grid_sort_03);
			} else {
				listResult.setVisibility(View.GONE);
				gridResult.setVisibility(View.VISIBLE);
				gridAdapter = new NhabepGridAvapter(this,
						objCookpads);
				gridResult.setAdapter(gridAdapter);
				btnSortDisplay.setImageResource(R.drawable.ic_list_sort_05);
			}
		}
		
	
	void layCongthuctheothanhphan(int page) {
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
				hiddenProgessDialog();
				btnSortDisplay.setEnabled(true);
				btnLoadMore.setText("Lấy thêm công thức");
				progressBarLoadmore.setVisibility(View.GONE);
				progressBar2.setVisibility(View.GONE);
			}

			@Override
			public void onSuccess(JSONObject re) {
				try {
					int status = re.getInt("status");
					if (status == 200) {
						btnSortDisplay.setEnabled(true);
						progressBar.setVisibility(View.GONE);
						progressBarLoadmore.setVisibility(View.GONE);
						progressBar2.setVisibility(View.GONE);
						btnLoadMore.setText("Lấy thêm công thức");
						JSONObject data = re.getJSONObject("data");
						Log.i("DATA", "Nhan dc: "+data.toString());
						JSONArray items = data.getJSONArray("items");
						if (items.length() == 0) {
							footerMain.setVisibility(View.GONE);
							progressBarLoadmore.setVisibility(View.GONE);
							noRs.setVisibility(View.VISIBLE);
							return;
						}
						for (int i = 0; i < items.length(); i++) {
							JSONObject item = items.getJSONObject(i);

							String id = item.getString("id");
							String name = item.getString("name");
							String desc = item.getString("desc");
							
							
							int viewCount = item.getInt("view_count");
							int likeCount = item.getInt("like_count");

							ObjCookpad objCookpad = new ObjCookpad();
							Object tacgia = item.get("author");
							if (tacgia instanceof JSONObject) {
								JSONObject jsonObj = (JSONObject) tacgia;
								objCookpad.setNamePersonCookpad(jsonObj
										.getString("name"));
								objCookpad.setIdNamePerson(jsonObj.getString("id"));
							} else if (tacgia instanceof JSONArray) {
								JSONArray jsonArray = (JSONArray) tacgia;
								objCookpad
										.setNamePersonCookpad("Vô danh");
								
							}

							objCookpad.setId(id);
							objCookpad.setNameCookpad(name);
							objCookpad.setDescriptionCookpad(desc);
							// getImage
							JSONObject image = item.getJSONObject("image");
							objCookpad.setUrlImageCookpad(image.getString("cover"));
							objCookpad.setViewedCookpad(viewCount);
							objCookpad.setLikeCookpad(likeCount);
							objCookpad.setThoigianNauan(item.getString("time"));
							
							objCookpads.add(objCookpad);

						}
						isLoading = false;
//						listAdapter.notifyDataSetChanged();
						footerMain.setVisibility(View.VISIBLE);
					} else {
						hiddenProgessDialog();
						btnLoadMore.setText("Lấy thêm công thức");
						progressBarLoadmore.setVisibility(View.GONE);
					}
					
				} catch (JSONException e) {
					e.printStackTrace();
					hiddenProgessDialog();
					btnLoadMore.setText("Lấy thêm công thức");
					progressBarLoadmore.setVisibility(View.GONE);
				}
			}
			
		});
		
		httpClientHelper.searchMonan("", createFilter(), page, "like");
	}
	
	
	 public JSONObject createFilter() {
		JSONObject filter = new JSONObject();
		try {
			filter.put(alias, aliasDetail);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return filter;
	}
	
	// hide progress bar
		void hiddenProgessDialog() {
			try {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						try {
							progressBar.setVisibility(View.GONE);
						} catch (Exception e) {
						}
					}
				});
			} catch (Exception e) {
			}
		}
		
		// add footer view cong thuc da dang
		void addFooterView() {
			View loadMoreView = ((LayoutInflater) this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
					R.layout.footer_loadmore, null, false);
			footerMain = (View) loadMoreView.findViewById(R.id.footer_main);
			footerMain.setVisibility(View.GONE);
			listResult.addFooterView(loadMoreView);
			btnLoadMore = (Button) loadMoreView.findViewById(R.id.btn_load_more);
			progressBarLoadmore = (ProgressBar) loadMoreView.findViewById(R.id.progressBar1);
			btnLoadMore.setOnClickListener(this);
		}


		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub
			
		}	
		
		void closeActivity(){
			finish();
			overridePendingTransition(R.anim.open_main, R.anim.close_next);
		}


		@Override
		public void onBackPressed() {
			closeActivity();
		}

		
}
